//
//  RJCheckDataTypeSegment.m
//  AirQuality
//
//  Created by Po on 15/6/26.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCheckDataTypeSegment.h"

@interface RJCheckDataTypeSegment ()

@property (retain, nonatomic) NSMutableArray * buttonsArray;
@property (retain, nonatomic) UIButton * currentButton;

@end

@implementation RJCheckDataTypeSegment

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initInterface];
    }
    return self;
}

- (void)initInterface
{
    NSArray * titles = @[@"全部数据",@"可疑数据"];
    _buttonsArray = [[NSMutableArray alloc] init];
    CGFloat width = self.frame.size.width / titles.count;
    CGFloat height = self.frame.size.height;
    
    for (NSUInteger i = 0; i < titles.count; i ++) {
        UIButton * button = [self createButtonWithFrame:CGRectMake(width * i, 0, width, height) title:titles[i]];
        if (i == 0) {
            [button setSelected:YES];
            _currentButton = button;
            [_currentButton setBackgroundColor:SysMainColor];
        } else {
            [button setBackgroundColor:GetRGBColor(245, 245, 245, 1)];
        }
        [_buttonsArray addObject:button];
        [self addSubview:button];
    }
}

#pragma mark - event
- (void)pressButton:(UIButton *)sender
{
    if (_currentButton == sender) {
        return;
    }
    [_currentButton setSelected:NO];
    [_currentButton setBackgroundColor:GetRGBColor(245, 245, 245, 1)];
    _currentButton = sender;
    [_currentButton setSelected:YES];
    [_currentButton setBackgroundColor:SysMainColor];
    if (_delegate) {
        [_delegate CheckDataTypeSegmentDidSelectCount:[_buttonsArray indexOfObject:_currentButton] type:_currentButton.titleLabel.text];
    }
}

- (void)setSelectCount:(NSUInteger)count
{
    UIButton * button = [_buttonsArray objectAtIndex:count];
    if (_currentButton == button) {
        return;
    }
    [_currentButton setSelected:NO];
    _currentButton = button;
    [_currentButton setSelected:YES];
}

#pragma mark - getter
- (UIButton *)createButtonWithFrame:(CGRect)frame title:(NSString *)title
{
    UIButton * button = [[UIButton alloc] initWithFrame:frame];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(pressButton:) forControlEvents:UIControlEventTouchUpInside];
    [button setSelected:NO];
    return button;
}

@end
